# -*- coding: utf-8 -*-

import subprocess

def line_to_path(line):
    line_list = line.split(" ", 1)
    if len(line_list) == 2:
        path = line_list[1]
        return path.strip()
    else: 
        return ""


def batch_commit(svn_url, local_path, batch_size):
    # 获取本地工作副本状态
    status_output = subprocess.Popen(['svn', 'status', local_path], stdout=subprocess.PIPE).communicate()
    status = status_output[0].decode('gb2312')  # 使用 gb2312 解码

    # print(status)

    # 根据 status 获取需要提交的文件路径列表
    files_to_commit = []    
    files_to_add = []
    files_to_delete = []
    for line in status.split('\n'):
        if (line.find("EditCache") == -1):
            path = line_to_path(line)
            # print(path)
            if line.startswith('M') or line.startswith('A') or line.startswith('D'):
                files_to_commit.append(path)
            elif line.startswith('?'):
                files_to_add.append(path)
                files_to_commit.append(path)
            elif line.startswith('!'):
                files_to_delete.append(path)
                files_to_commit.append(path)

    total_count = len(files_to_commit)

    print("----------------------status total_count")
    print(total_count)
    print("----------------------status")

    # 分批提交文件
    for i in range(0, total_count, batch_size):
        batch_files = files_to_commit[i:i + batch_size]

        # 执行每个文件的提交
        for file in batch_files:
            if file in files_to_add:
                subprocess.Popen(['svn', 'add', file]).communicate()
            elif file in files_to_delete:
                subprocess.Popen(['svn', 'delete', file]).communicate()
            
        subprocess.Popen(['svn', 'commit', '-m', 'Batch commit asset:' + str(i + len(batch_files)) + "/" + str(total_count)] + batch_files).communicate()
        print("----------------Batch commit asset:" + str(i + len(batch_files)) + "/" + str(total_count))

if __name__ == '__main__':
    svn_url = 'https://desktop-9b76kur/svn/Res_Wuhlan'                  # svn仓库url
    local_path = 'C:/WorkPlace/SVN_WorkSpace/SVN_AutoCommitTest'        # 本地SVN路径
    batch_size = 100                                                    # 批次大小

    batch_commit(svn_url, local_path, batch_size)
